package com.wang.mvchain.users.service.implay;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Callable;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wang.mvchain.common.service.BaseServiceImplay;
import com.wang.mvchain.common.util.ConstatFinalUtil;
import com.wang.mvchain.common.util.ExecutorServiceUtil;
import com.wang.mvchain.common.util.PageInfoUtil;
import com.wang.mvchain.outer.IOutTimerService;
import com.wang.mvchain.outer.service.ITradeService;
import com.wang.mvchain.outer.util.TradeUtil;
import com.wang.mvchain.system.pojo.ACoinrate;
import com.wang.mvchain.system.pojo.ACoinrateEnum;
import com.wang.mvchain.system.service.IWebsiteService;
import com.wang.mvchain.users.dao.IAAdminsDAO;
import com.wang.mvchain.users.dao.IAUsersAccountDAO;
import com.wang.mvchain.users.dao.IAUsersDAO;
import com.wang.mvchain.users.pojo.AAdmins;
import com.wang.mvchain.users.pojo.AUsers;
import com.wang.mvchain.users.pojo.AUsersAccount;
import com.wang.mvchain.users.service.IUsersService;
import com.wang.mvchain.util.ServiceCallableUtil;

/**
 * 用户的实现类
 * 
 * @author wangshmac
 *
 */
@Service("usersService")
public class UsersServiceImplay extends BaseServiceImplay implements IUsersService
{
	@Autowired
	private IAAdminsDAO adminsDAO;
	@Autowired
	private IAUsersDAO usersDAO;
	@Autowired
	private IAUsersAccountDAO usersAccountDAO;
	
	@Autowired
	private IWebsiteService websiteService;
	@Resource
	private IOutTimerService outTimerService;

	@Override
	public JSONObject saveOneAdminsService(AAdmins admins)
	{
		JSONObject resultJSON = new JSONObject();
		// 查询用户的单点登陆id是否存在
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("ssoid", admins.getSsoid() + "");
		AAdmins adminRes = this.findOneAdminsService(condMap);
		if (adminRes != null)
		{
			resultJSON.put("code", "-1");
			resultJSON.put("info", "此单点登陆管理员已经存在");
			return resultJSON;
		}
		int res = this.adminsDAO.save(admins);
		if (res > 0)
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "添加成功");
		} else
		{
			resultJSON.put("code", "-2");
			resultJSON.put("info", "添加失败");
		}
		return resultJSON;
	}

	@Override
	public JSONObject updateOneAdminsService(AAdmins admins)
	{
		JSONObject resultJSON = new JSONObject();

		// 查询用户的单点登陆id是否存在
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("ssoid", admins.getSsoid() + "");
		AAdmins adminRes = this.findOneAdminsService(condMap);
		if (adminRes != null && adminRes.getId() != admins.getId())
		{
			resultJSON.put("code", "-1");
			resultJSON.put("info", "此单点登陆管理员已经存在");
			return resultJSON;
		}

		int res = this.adminsDAO.update(admins);
		if (res > 0)
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "更新成功");
		} else
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "更新失败");
		}
		return resultJSON;
	}

	@Override
	public JSONObject deleteOneAdminsService(AAdmins admins)
	{
		JSONObject resultJSON = new JSONObject();
		int res = this.adminsDAO.delete(admins);
		if (res > 0)
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "删除成功");
		} else
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "删除失败");
		}
		return resultJSON;
	}

	@Override
	public List<AAdmins> findCondListAdminsService(PageInfoUtil pageInfoUtil,Map<String, Object> condMap)
	{
		List<AAdmins> adminsList = Collections.emptyList() ; 
		if(pageInfoUtil != null)
		{
			//分页查询数据
			Page<AAdmins> pageInfo = PageHelper.startPage(pageInfoUtil.getCurrentPage(), pageInfoUtil.getPageSize());
			adminsList = this.adminsDAO.findList(condMap);
			//设置总记录数
			pageInfoUtil.setTotalRecord(Long.valueOf(pageInfo.getTotal()).intValue());
		}else
		{
			adminsList = this.adminsDAO.findList(condMap);
		}
		return adminsList;
	}

	@Override
	public AAdmins findOneAdminsService(Map<String, Object> condMap)
	{
		return this.adminsDAO.findOne(condMap);
	}

	@Override
	public JSONObject saveOneUsersService(AUsers users)
	{
		JSONObject resultJSON = new JSONObject();
		// 查询用户的单点登陆id是否存在
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("ssoid", users.getSsoid() + "");
		AUsers usersRes = this.findOneUsersService(condMap);
		if (usersRes != null)
		{
			resultJSON.put("code", "-1");
			resultJSON.put("info", "此单点用户员已经存在");
			return resultJSON;
		}
		int res = this.usersDAO.save(users);
		if (res > 0)
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "添加成功");
		} else
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "添加失败");
		}
		return resultJSON;
	}

	@Override
	public JSONObject updateOneUsersService(AUsers users)
	{
		JSONObject resultJSON = new JSONObject();

		// 查询用户的单点登陆id是否存在
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("ssoid", users.getSsoid() + "");
		AUsers usersRes = this.findOneUsersService(condMap);
		if (usersRes != null && usersRes.getId() != users.getId())
		{
			resultJSON.put("code", "-1");
			resultJSON.put("info", "此单点用户已经存在");
			return resultJSON;
		}

		int res = this.usersDAO.update(users);
		if (res > 0)
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "更新成功");
		} else
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "更新失败");
		}
		return resultJSON;
	}

	@Override
	public JSONObject deleteOneUsersService(AUsers users)
	{
		JSONObject resultJSON = new JSONObject();
		int res = this.usersDAO.delete(users);
		if (res > 0)
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "删除成功");
		} else
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "删除失败");
		}
		return resultJSON;
	}

	@Override
	public AUsers findOneUsersService(Map<String, Object> condMap)
	{
		AUsers users = this.usersDAO.findOne(condMap);
		if("true".equalsIgnoreCase(condMap.get("extend") + "") && users != null)
		{
			
			Map<String, Object> paramsMap = new HashMap<String, Object>();
			paramsMap.put("users", users);
			
			ServiceCallableUtil multiThreadUtil = new ServiceCallableUtil();
			multiThreadUtil.setParamsMap(paramsMap);
			multiThreadUtil.setOutTimerService(this.outTimerService);
			multiThreadUtil.setOperType("updateBatchUsersInfoService");
			
			try
			{
				/* 提交线程 */
				if("wait".equalsIgnoreCase(condMap.get("threadType") + ""))
				{
					List<Callable<Object>> threadList = new ArrayList<Callable<Object>>();
					threadList.add(multiThreadUtil);
					ExecutorServiceUtil.invokeAll(threadList);
				}else
				{
					ExecutorServiceUtil.submit(multiThreadUtil);
				}
			} catch (InterruptedException e)
			{
				ExecutorServiceUtil.shutdown();
			}
		}
		return users; 
	}

	@Override
	public List<AUsers> findCondListUsersService(PageInfoUtil pageInfoUtil, Map<String, Object> condMap)
	{
		List<AUsers> usersList = Collections.emptyList() ; 
		if(pageInfoUtil != null)
		{
			//分页查询数据
			Page<AUsers> pageInfo = PageHelper.startPage(pageInfoUtil.getCurrentPage(), pageInfoUtil.getPageSize());
			usersList = this.usersDAO.findList(condMap);
			pageInfoUtil.setTotalRecord(Long.valueOf(pageInfo.getTotal()).intValue());
		}else
		{
			usersList = this.usersDAO.findList(condMap);
		}
		return usersList;
	
	}

	@Override
	public JSONObject saveOneUsersAccountService(AUsersAccount usersAccount)
	{
		int succedCount = 0 ; 
		Map<String, Object> condMap = new HashMap<String, Object>();
		JSONObject resultJSON = new JSONObject();
		
		//判断一下用户否是否已经存在
		/*condMap.clear();
		condMap.put("keywordEq", usersAccount.getUsername());
		condMap.put("wbid", usersAccount.getWbid() + "");
		List<AUsersAccount> usersAccountList = this.findCondListUsersAccountService(new PageInfoUtil() , condMap );
		if(usersAccountList.size() > 0)
		{
			resultJSON.put("code", "-2");
			resultJSON.put("info", "添加失败,此网站用户名已经存在");
			return resultJSON ;
		}*/
		
		//根据网站id和认证信息查询账户信息
		ITradeService tradeService = TradeUtil.tradeServiceMap.get(usersAccount.getWbid() + "");
		tradeService.setAuthJSON(usersAccount.getAuthinfoJSON());
		JSONObject tradeResJSON = tradeService.getUserInfo(new HashMap<String, String>());
		if(tradeResJSON != null && "0".equalsIgnoreCase(tradeResJSON.get("code") + ""))
		{
			JSONObject dataJSON = (JSONObject) tradeResJSON.get("data");
			JSONObject balanceJSON = (JSONObject) dataJSON.get("balance") ;
			JSONObject fundJSON = (JSONObject) dataJSON.get("fund") ;
			for (Iterator iterator = balanceJSON.entrySet().iterator(); iterator.hasNext();)
			{
				Entry me = (Entry) iterator.next();
				String key = me.getKey() + "" ;
				String value = me.getValue() + "" ;
				
				//查询币种id
				condMap.clear();
				condMap.put("engname", key.toUpperCase());
				ACoinrate coinrate = this.websiteService.findOneCoinrateService(condMap);
				if(coinrate == null || coinrate.getStatus() == ACoinrateEnum.STATUS_DISABLE.getStatus())
				{
					/* 说明系统中木有此币种,暂时不支持 */
					continue ; 
				}
				/* 判断一下,如果usersAccount是否存在 */
				condMap.clear();
				condMap.put("keywordEq", usersAccount.getUsername());
				condMap.put("coinid", coinrate.getId() + "");
				condMap.put("usersid", usersAccount.getUsersid() + "");
				condMap.put("wbid", usersAccount.getWbid() + "");
				List<AUsersAccount> usersAccountList = this.findCondListUsersAccountService(new PageInfoUtil() , condMap );
				AUsersAccount usersAccountRes = new AUsersAccount();
				
				boolean updateFlag = false ; 
				if(usersAccountList.size() > 0)
				{
					usersAccountRes = usersAccountList.get(0);
					updateFlag = true ; 
				}else
				{
					usersAccountRes.setStatus(Byte.valueOf("1"));
					usersAccountRes.setCreatetime(new Date());
				}
				
				usersAccountRes.setUsersid(usersAccount.getUsersid());
				usersAccountRes.setWbid(usersAccount.getWbid());
				usersAccountRes.setUsername(usersAccount.getUsername());
				usersAccountRes.setAuthinfo(usersAccount.getAuthinfo());
				
				usersAccountRes.setBalance(Double.valueOf(value));
				usersAccountRes.setFundmoney(Double.valueOf(fundJSON.get(key) + ""));
				
				usersAccountRes.setUpdatetime(new Date());
				usersAccountRes.setPubtime(new Date());
				
				usersAccountRes.setCoinid(coinrate.getId());
				
				PageInfoUtil pageInfoUtil = new PageInfoUtil();
				//查询交易配置
				condMap.clear();
				condMap.put("coinid", coinrate.getId() + "");
				usersAccountList = this.findCondListUsersAccountService(pageInfoUtil,condMap);
				if(pageInfoUtil.getTotalPage() > 0)
				{
					AUsersAccount usersAccountTemp = usersAccountList.get(0);
					usersAccountRes.setTrademaxnum(usersAccountTemp.getTrademaxnum());
					usersAccountRes.setPrift(usersAccountTemp.getPrift());
				}
				
				int res = 0 ;
				//入库
				if(updateFlag)
				{
					this.updateOneUsersAccountService(usersAccountRes);
				}else
				{
					res = this.usersAccountDAO.save(usersAccountRes);
				}
				if(res > 0 )
				{
					succedCount ++ ;
				}
			}
		}
		
		if (succedCount > 0)
		{
			resultJSON.put("code", succedCount + "");
			resultJSON.put("info", "添加成功,影响条数:" + succedCount);
		} else
		{
			resultJSON.put("code", "-1");
			resultJSON.put("info", "添加失败,影响条数:" + succedCount);
		}
		return resultJSON;
	}

	@Override
	public JSONObject updateOneUsersAccountService(AUsersAccount usersAccount)
	{
		JSONObject resultJSON = new JSONObject();
		int res = this.usersAccountDAO.update(usersAccount);
		if (res > 0)
		{
			resultJSON.put("code", res + "");
			resultJSON.put("info", "更新成功,影响条数:" + res);
		} else
		{
			resultJSON.put("code", res + "");
			resultJSON.put("info", "更新失败,影响条数:" + res);
		}
		return resultJSON;
	}
	
	@Override
	public JSONObject updateBatchUsersAccountService(String type , List<AUsersAccount> usersAccountList)
	{
		JSONObject resultJSON = new JSONObject();
		int res = 0 ; 
		if("1".equalsIgnoreCase(type))
		{
			if(usersAccountList.size() > 0 )
			{
				//批量增加
				res = this.usersAccountDAO.saveBatch(usersAccountList);
			}
		}else if("2".equalsIgnoreCase(type))
		{
			if(usersAccountList.size() > 0 )
			{
				//批量更新
				res = this.usersAccountDAO.updateBatch(usersAccountList);
			}
		}
		resultJSON.put("code", "0");
		resultJSON.put("info", "批量操作成功,总条数:"+ usersAccountList.size() +";成功条数:" + res);
		return resultJSON ; 
	}
	
	@Override
	public JSONObject updateBatchUsersAccountService(String type , AUsersAccount usersAccount)
	{
		JSONObject resultJSON = new JSONObject();
		int res = 0 ; 
		if("updatePrift".equalsIgnoreCase(type))
		{
			//仅更新收益
			res = this.usersAccountDAO.updatePrift(usersAccount);
		}else if("updateAuditInfo".equalsIgnoreCase(type))
		{
			res = this.usersAccountDAO.updateAuditInfo(usersAccount);
		}else if("updateUpdateTime".equalsIgnoreCase(type))
		{
			res = this.usersAccountDAO.updateUpdateTime(usersAccount);
		}
		if (res > 0)
		{
			resultJSON.put("code", res + "");
			resultJSON.put("info", "更新成功,影响条数:" + res);
		} else
		{
			resultJSON.put("code", res + "");
			resultJSON.put("info", "更新失败,影响条数:" + res);
		}
		return resultJSON;
	}

	@Override
	public JSONObject deleteOneUsersAccountService(AUsersAccount usersAccount)
	{
		JSONObject resultJSON = new JSONObject();
		int res = this.usersAccountDAO.delete(usersAccount);
		if (res > 0)
		{
			resultJSON.put("code", res + "");
			resultJSON.put("info", "删除成功");
		} else
		{
			resultJSON.put("code", res + "");
			resultJSON.put("info", "删除失败");
		}
		return resultJSON;
	}

	@Override
	public AUsersAccount findOneUsersAccountService(Map<String, Object> condMap)
	{
		AUsersAccount usersAccount =  this.usersAccountDAO.findOne(condMap);
		return usersAccount ; 
	}

	@Override
	public List<AUsersAccount> findCondListUsersAccountService(PageInfoUtil pageInfoUtil, Map<String, Object> condMap)
	{
		List<AUsersAccount> usersAccountList = Collections.emptyList() ; 
		/*
		 * 是否放缓存
		 * 键的类型为treeMap,键为:条件下划线隔开,值为数组
		 * */
		StringBuffer keySb = new StringBuffer();
		if("true".equalsIgnoreCase(condMap.get("cache") + ""))
		{
			keySb.append("usersAccountList-->");
			for (Iterator iterator = condMap.entrySet().iterator(); iterator.hasNext();)
			{
				Entry me = (Entry) iterator.next();
				keySb.append(me.getKey() + ":" + me.getValue() + ";");
			}
			
			if(pageInfoUtil != null)
			{
				keySb.append("currentPage" + ":" + pageInfoUtil.getCurrentPage() + ";");
				keySb.append("pageSize" + ":" + pageInfoUtil.getPageSize() + ";");
			}
			
			/* 从缓存中取数据 */
			String redisResult = this.redisUtil.get(keySb + "") + ""; 
			if(!"".equalsIgnoreCase(redisResult) && !"null".equalsIgnoreCase(redisResult))
			{
				usersAccountList = new ArrayList<AUsersAccount>();
				JSONArray resultArr = (JSONArray) JSON.parse(redisResult);
				if(resultArr != null)
				{
					//说明有值
					for (Iterator iterator = resultArr.iterator(); iterator.hasNext();)
					{
						JSONObject jsonObj = (JSONObject) iterator.next();
						AUsersAccount usersAccount = new AUsersAccount();
						usersAccount = usersAccount.parseJSON(jsonObj);
						usersAccountList.add(usersAccount);
					}
					//ConstatFinalUtil.SYS_LOG.info("usersAccountList从redis中读取,键为:{},数据条数:{}",keySb , usersAccountList.size());
					/*从redis中取到数据,直接返回*/
					return usersAccountList ; 
				}
			}
		}
		
		if(pageInfoUtil != null)
		{
			Page<AUsersAccount> pageInfo = PageHelper.startPage(pageInfoUtil.getCurrentPage(), pageInfoUtil.getPageSize());
			usersAccountList = this.usersAccountDAO.findList(condMap);
			pageInfoUtil.setTotalRecord(Long.valueOf(pageInfo.getTotal()).intValue());
		}else
		{
			usersAccountList = this.usersAccountDAO.findList(condMap);
		}
		if("true".equalsIgnoreCase(condMap.get("cache") + ""))
		{
			if(usersAccountList.size() > 0 )
			{
				//往缓存里面放数据
				JSONArray resultArr = new JSONArray();
				for (Iterator iterator = usersAccountList.iterator(); iterator.hasNext();)
				{
					AUsersAccount usersAccount = (AUsersAccount) iterator.next();
					resultArr.add(usersAccount.toJSON());
				}
				int time = Integer.valueOf(condMap.get("expirTime") + "");
				if(!this.redisUtil.put(keySb + "", resultArr + "" , time))
				{
					ConstatFinalUtil.SYS_LOG.error("放置redis缓存失败了,键为:",keySb);
				}
			}
		}
		return usersAccountList ; 
	}

	@Override
	public List<Map<String, Object>> findUsersAccountStatListService(PageInfoUtil pageInfoUtil,Map<String, Object> condMap)
	{
		List usersAccountList = Collections.emptyList() ; 
		if(pageInfoUtil != null)
		{
			PageHelper.startPage(pageInfoUtil.getCurrentPage(), pageInfoUtil.getPageSize());
			usersAccountList = this.usersAccountDAO.findStatList(condMap);
			PageInfo pageInfo = new PageInfo(usersAccountList);
			usersAccountList = pageInfo.getList();
			pageInfoUtil.setTotalRecord(Long.valueOf(pageInfo.getTotal()).intValue());
		}else
		{
			usersAccountList = this.usersAccountDAO.findStatList(condMap);
		}
		Map<String, Object> extMap = new HashMap<String, Object>();
		for (Iterator iterator = usersAccountList.iterator(); iterator.hasNext();)
		{
			Map	me = (Map) iterator.next();
			
			extMap.put("id", me.get("coinid") + "");
			ACoinrate coinrate = this.websiteService.findOneCoinrateService(extMap);
			me.put("coinrate", coinrate);
		}
		return usersAccountList ; 
	}
}
